package za.co.johanmynhardt.jsf.bean;

import java.io.IOException;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import za.co.johanmynhardt.jee.entity.Post;
import za.co.johanmynhardt.jee.entity.User;
import za.co.johanmynhardt.jee.service.PostService;

/**
 * @author johan.mynhardt@thumbtribe.mobi
 * @version 2011.1218
 */
@ManagedBean
@ViewScoped
public class CreatePostBean implements Serializable {
	private String title;
	private Date date = Calendar.getInstance().getTime();
	private User user;
	private String content;
	
	private final Logger logger = Logger.getLogger(CreatePostBean.class.getName());

	@EJB
	private PostService service;

	public void savePost(ActionEvent actionEvent) {
		logger.info("Title: " + title);
		logger.info("Date: " + date);
		logger.info("Content: " + content);

		Post post = new Post();
		post.setTitle(title);
		post.setUser(user);
		post.setDate(date);
		post.setContent(content);

		service.savePost(post);
		
		try {
			FacesContext.getCurrentInstance().getExternalContext().redirect("post.jsf");
		} catch (IOException e) {
			logger.severe("Could not save post: " + e.getMessage());
		}
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}
}
